package org.example.cloud.others.utils;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;


@Data
@Slf4j
public class AccessToken {
    private static String accessToken;
    private static Integer expiresIn;
    private static Long expiresTime;//过期时间

    public AccessToken() {
    }

//    public AccessToken(String accessToken, Integer expiresIn) {
//        this.accessToken = accessToken;
//        this.expiresIn = expiresIn;
//        this.expiresTime = System.currentTimeMillis() + expiresIn * 1000;
//    }

    //判断accessToken是否失效   false 未失效
    public boolean isExpired() {
        return System.currentTimeMillis() > expiresTime;
    }

    /**
     * 获取access_token
     * access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
     *
     * @return
     */
    public static String initAccessToken() {
        String requestUrl = Constants.ACCESS_TOKEN_URL.replace("APPID", VX.appID).replace("APPSECRET", VX.appsecret);
        JSONObject jsonObject = HttpUtil.doGetstr(requestUrl);
        if (null != jsonObject) {
            try {
                accessToken = jsonObject.getString("access_token");
                expiresIn = jsonObject.getInteger("expires_in");
                expiresTime = System.currentTimeMillis() + expiresIn * 1000;
            } catch (JSONException e) {
                accessToken = null;
                // 获取token失败
                log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInteger("errcode"), jsonObject.getString("errmsg"));
            }
        }
        System.out.println(accessToken);
        return accessToken;
    }

    /**
     * 获取微信accessToken   默认为 不刷新accessToken
     *
     * @return
     */
    public static synchronized String getAccessToken() {
        return getAccessToken(false);
    }

    public static synchronized String getAccessToken(boolean refresh) {
        if (StringUtils.isBlank(accessToken) || System.currentTimeMillis()  > expiresTime || refresh) {
            accessToken = initAccessToken();
        }
        return accessToken;
    }

}
